package StudyCode.summary.BufferAndChannel;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SeekableByteChannel;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.EnumSet;

/**
 * 版权所有 科技与人文(www.tah1986.com)
 */
public class ReadOneCharacterSeekableByteChannel {
	public static void main(String[] args) {
		Path path = Paths.get("E:\\Copy", "1.txt");
		ByteBuffer buffer = ByteBuffer.allocate(1);
		String encoding = System.getProperty("file.encoding");

		try (SeekableByteChannel seekableByteChannel = (Files.newByteChannel(path, EnumSet.of(StandardOpenOption.READ)))) {
			seekableByteChannel.position(0);
			System.out.println("从指定位置读取字符: " + seekableByteChannel.position());
			seekableByteChannel.read(buffer);
			buffer.flip();
			System.out.print(Charset.forName(encoding).decode(buffer));
			buffer.rewind();

			seekableByteChannel.position(seekableByteChannel.size() / 2);

			System.out.println("\n从指定位置读取字符: " + seekableByteChannel.position());
			seekableByteChannel.read(buffer);
			buffer.flip();
			System.out.print(Charset.forName(encoding).decode(buffer));
			buffer.rewind();

			seekableByteChannel.position(seekableByteChannel.size() - 1);

			System.out.println("\n从指定位置读取字符: " + seekableByteChannel.position());

			seekableByteChannel.read(buffer);
			buffer.flip();
			System.out.print(Charset.forName(encoding).decode(buffer));
			buffer.clear();

		} catch (IOException ex) {
			System.err.println(ex);
		}
	}
}
